<?php
	include('Afun_cache.php');
	@header("Content-Type: text/html; charset=utf-8");
	
	$pcre_utf8 = '\x{4e00}-\x{9fa5}';
	$pcre_gbk = '\xB0-\xF7\xA1-\xFE\x81-\xA0\x40-\xFE\xAA-\xFE\x40-\xA0';
	@set_time_limit(0);
	function curl_redir_exec($ch,$debug=""){
		static $curl_loops = 0;
		static $curl_max_loops = 20;
		if ($curl_loops++ >= $curl_max_loops){
			$curl_loops = 0;
			return FALSE;
		}
		curl_setopt($ch, CURLOPT_HEADER, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$data = curl_exec($ch);
		
		$debbbb = $data;
		list($header, $data) = explode("\n\n", $data, 2);
		$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		if ($http_code == 301 || $http_code == 302){
			$matches = array();
			preg_match('/Location:(.*?)\n/', $header, $matches);
			$url = @parse_url(trim(array_pop($matches)));
			if (!$url){
				$curl_loops = 0;
				return $data;
			}
			$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
			$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
			curl_setopt($ch, CURLOPT_URL, $new_url);
			return curl_redir_exec($ch);
		} else {
			$curl_loops=0;
			return $debbbb;
		}
	}
	function index_baidu($str){
		global $pcre_utf8;
		$cname = 'chinaz_'.$str;
		$obj = Afun_cache_get($cname);
		if(!$obj){
			$url = 'http://tool.chinaz.com/baidu/words.aspx?kw='.$str;
			$post_data = array('kw'=>$str,'submit1'=>'查 询','search'=>'1');
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
			$file_contents = curl_redir_exec($curl);
			curl_close($curl);
			$file_contents = str_replace(array("\r","\n",'<em>','</em>'),array('','','',''),$file_contents);
			preg_match('/<table class="seo"  cellpadding="5" cellspacing="1">(.+)<\/table>/iu',$file_contents,$prr);
			$prrs = preg_replace(array('/(<([\/]*)span([\w\s\d\;\/\%\.\?\+ "=:_-]*)>)/','(<img([\w\s\d\;\/\%\.\?\+\&| "=:_-]*)>)'),array('',''),$prr[1]);
			$guize = '/<td class="id">([0-9]{1,2}|100)<\/td>([\r\n ]*)';
			$guize .= '<td class="kw"><a ([\w\s\d\/\%\.\?\+ "=:_-]+?)>([\w\s\d\.\/ &\%!?*-_~#"\''.$pcre_utf8.']+?)<\/a><\/td>([\r\n ]*)';
			$guize .= '<td ><a ([\w\s\d\/\%\.\?\+ "=:_-]+?)>([\w\s\d\/\.\%\?\+ "=:_-]*?)<\/a><\/td>([\r\n ]*)';
			$guize .= '<td ><a ([\w\s\d\/\%\.\?\+ "=:_-]+?)>([\w\s\d\/\.\%\?\+ "=:_-]*?)<\/a><\/td>([\r\n ]*)';
			$guize .= '<td ><a ([\w\s\d\/\%\.\?\+ "=:_-]+?)>([\w\s\d\/\.\%\?\+ "=:_-]*?)<\/a><\/td>([\r\n ]*)';
			$guize .= '<td class="host"><a ([\w\s\d\/\%\.\?\+ "=:_-]+?)>([\w\s\d\/\.\%\?\+ "=:_-]*?)<\/a>/u';
			preg_match_all($guize,$prrs,$drr);
			for($i=0;$i<count($drr[1]);$i++){
				$obj[$drr[4][$i]]['index'] = $drr[10][$i];
				$obj[$drr[4][$i]]['url'] = $drr[16][$i];
			}
			Afun_cache_set($cname,$obj,3600);
		}
		return $obj;
	}
	function list_baidu_url($url){
		global $pcre_utf8;
		$file_contents = open_url($url);
		$file_contents = str_replace(array("\r","\n",'<b>','</b>','<em>','</em>'),array('','','','','',''),$file_contents);
		$file_contents = preg_replace(array('/<style >(.+?)<\/style>/i','/<script>(.+?)<\/script>/i'),array('',''),$file_contents);
		preg_match_all('/<table([\w\s\d "=_-]+?) id="([0-9]{1,2}|100)"(.*?)<\/table>/iu',$file_contents,$prr);
		$num = count($prr[0]);
		$index = 0;
		$info['pn'] = 0;
		for ($i=0;$i<$num;$i++) {
			$arr['id'] = $prr[2][$i];
			preg_match('/(<span class="g">|<font color="#008000">)([\w\s\d\.\/\?\*\|$&\%;{}!()-_~#]+?)([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})([ ]*?)(<\/span>|<\/font>)/i',$prr[3][$i],$drr);
			if(empty($drr)){
				preg_match('/href="(http|https):\/\/([\w\s\d\.\/\|$&\%;{}!()?*-_~#]{3,50})"/iu',$prr[3][$i],$drr);
			}else{
				$drr[2] = preg_replace('/<(.+?)>/i',"",trim($drr[2]));
			}
			$urlrr = explode("/",$drr[2]);
			$arr['url'] = $drr[2];
			$arr['host'] = $urlrr[0];
			if(!empty($urlrr[0]) && $urlrr[1]==''){
				$info['pn']++;
			}
			if(!empty($drr[3]) && !empty($drr[4]) && !empty($drr[5])){
				$arr['date'] = $drr[3]."-".$drr[4]."-".$drr[5];
			}
			preg_match('/<h3 class="t">(.*)<\/h3>/iu',$prr[3][$i],$hrr);
			$arr['title'] = preg_replace('/<([\w\s\d\.\/\|$&\%\':"—;,{}!()?* -_~#'.$pcre_utf8.']*?)>/iu',"",$hrr[1]);
			preg_match('/href="(http|https):\/\/([\w\s\d\.\/\|$&\%;{}!()?*-_~#'.$pcre_utf8.']+?)"/iu',$hrr[1],$urr);
			$arr['link'] = $urr[2];
			if(substr($arr['link'],0,23)=='www.baidu.com/link?url='){
				$arr['link'] = '';
			}
			if(empty($arr['url'])) $arr['url'] = $arr['link'];
			if(empty($arr['link']) && !empty($arr['url'])) $arr['link'] = $arr['url'];
			$irr = explode('/',$arr['url']);
			if((count($irr)==2 && strlen($irr[1])==0) || count($irr)<2){$index++;}
			$data[] = $arr;
		}
		preg_match('/找到相关结(['.$pcre_utf8.']+?)([0-9,]+?)个/iu',$file_contents,$trr);
		$info['tatol'] = str_replace(",","",$trr[2]);
		$info['size'] = $num;
		$info['index'] = $index;
		$obj->info = $info;
		$obj->data = $data;
		return $obj;
	}
	function list_baidu($kw,$num=100){
		$kw = trim($kw);
		if(strlen($kw)==0){return;}
		$keyword = $kw;
		$cname = 'baidu_'.$keyword.$num;
		$data = Afun_cache_get($cname);
		if(!$data){
			//$kw = urlencode($kw);
			//$zhishu = index_baidu($keyword);
			//$data->info['index'] = $zhishu[$keyword]['index'];
			if($num>50){
				$url[] = "http://www.baidu.com/s?q1=$kw&rn=50";
				$url[] = "http://www.baidu.com/s?q1=$kw&pn=50&rn=".($num-50);
			}else{
				$url[] = "http://www.baidu.com/s?q1=$kw&rn=$num";
			}
			$data->info['key'] = $keyword;
			$data->info['pn'] = 0;
			for ($i=0; $i < count($url); $i++) {
				$obj = list_baidu_url($url[$i]);
				if(is_array($obj->data)){
					if(is_array($data->data)){
						$data->data = array_merge($data->data,$obj->data);
					}else{
						$data->data = $obj->data;
					}
				}
				if($obj->info['pn']>1) $data->info['pn'] += $obj->info['pn'];
				$data->info['size'] += $obj->info['size'];
				if($obj->info['tatol']>1) $data->info['tatol'] = $obj->info['tatol'];
			}
			Afun_cache_set($cname,$data,3600);
		}
		return $data;
	}
	function list_google($kw,$num=100){
		global $pcre_utf8;
		$kw = urlencode($kw);
		$url = "http://www.google.com.hk/search?hl=zh-CN&q=$kw&start=0&num=$num";
	//	$url = "http://www.google.com.hk/search?q=$kw&hl=zh-CN&num=$num&lr=lang_zh-CN&ft=i&cr=";
		$file_contents = open_urls($url);
		preg_match('/<ol>([\w\s\d\\\.\/\|$ &\%;{}!()?*-_~#"\''.$pcre_utf8.']+)<\/ol>/iu',$file_contents,$prr);
		$search = preg_replace('/<table([\w\s\d\\\.\/\|$ &\%;{}!()?*-_~#"\''.$pcre_utf8.']+?)<\/table>/u',"",$prr[1]);
		preg_match_all('/<li([\w\s\d\\\.\/\|$ &\%;{}!()?*-_~#"\''.$pcre_utf8.']+?)<\/li>/iu',$search,$qrr);
//		file_put_contents("./log.txt",$search);
		$num = count($qrr[0]);
		$index = 0;
		$index2 = 0;
		for ($i=0;$i<$num;$i++) {
			$arr['id'] = $i+1-$index2;
			preg_match('/<h3([\w\s\d\\\.\/\|$ &\%;{}!()?*-_~#"\''.$pcre_utf8.']+?)<\/h3>/iu',$qrr[0][$i],$hrr);
			$arr['title'] = preg_replace('/<([\w\s\d\\\.\/\|$ &\%;{}!()?*-_~#"\''.$pcre_utf8.']+?)>/u',"",$hrr[0]);
			preg_match('/href="(.*?)(http|https):\/\/([\w\s\d\.\/\|$&\%;{}!()?*-_~#'.$pcre_utf8.']+?)("|&amp;)/iu',$qrr[0][$i],$urr);
			$arr['url'] = urldecode($urr[3]);
			$irr = explode('/',$arr['url']);
			if((count($irr)==2 && strlen($irr[1])==0) || count($irr)<2){$index++;}
			if($arr['title']!="软件下载"){
				$data[] = $arr;
			}else{$index2++;}
		}
		preg_match('/(获得|找到约) ([0-9,]+?) /i',$file_contents,$trr);
		$info['tatol'] = str_replace(",","",$trr[2]);
		$info['size'] = $num;
		$info['key'] = urldecode($kw);
		$info['index'] = $index;
		$obj->info = $info;
		$obj->data = $data;
		return $obj;
	}
	function open_url($url){
		if(function_exists('curl_init')){
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
			curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
			//$file_contents = curl_exec($curl);
			$data = curl_redir_exec($curl);
			curl_close($curl);
		}
		return $data;
	}
	function open_urls($url){
		if(function_exists('curl_init')){
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_HTTPHEADER, array ("user_agent" => "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 (.NET CLR 3.5.30729)","language" => "en-us,en;q=0.5"));
			curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
		//	curl_setopt($curl, CURLOPT_FOLLOWLOCATION,1);
			curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
			curl_setopt($curl, CURLOPT_COOKIEJAR, dirname(__FILE__)."/cookie.txt");
			$data = curl_redir_exec($curl);
		//	$file_contents = curl_exec($curl);
			curl_close($curl);
		}
		return $data;
	}
	function seo_order($kw,$domain,$type='baidu',$num=100){
		if($type=='baidu'){
			$obj = list_baidu($kw,$num);
			if($domain) $shouru = list_baidu("site:".$domain,10);
		}else if($type=='google'){
			$obj = list_google($kw,$num);
		}
		if(is_array($obj->data) && !empty($domain)){
			foreach ($obj->data as $k => $v) {
				if(count(explode($domain,$v['url']))>1){
					if(empty($order)){$order = $v['id'];}
					if(empty($dates)){$dates = $v['date'];}
				}
			}
		}
		if(empty($order)){$order=0;}
		if($domain) $data['shouru'] = $shouru->info['tatol'];
		$data['order'] = $order;
		$data['date'] = $dates;
		return $data;
	}
	function Afun_charset($val,$charset="utf8",$type="text/html"){/*转换编码*/
		if(@in_array($charset,array("utf8","utf-8","UTF8","UTF-8"))||$charset==""){
		//	@header("Content-Type: ".$type."; charset=utf-8");
			$val = iconv('GB2312','utf-8',$val);
		}elseif(@in_array($charset,array("gbk","gb2312","GB2312","GB-2312"))){
		//	@header("Content-Type: ".$type."; charset=gb2312");
			$val = iconv('utf-8','GB2312//IGNORE',$val);
		}
		return $val;
	}
?>
